<template>
  <div class="login-container">
    <div class="form">
      <h1>登录</h1>
      <el-card shadow="never" class="login-card">
        <!--登录表单-->
        <el-form ref="formRef" :model="form" :rules="rules">
          <el-form-item prop="username">
            <el-input placeholder="请输入账号" v-model="form.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="请输入密码" v-model="form.password" show-password />
          </el-form-item>
          <el-form-item>
            <el-button style="width: 282px; height: 30px" type="primary" @click="loginbtn">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { loginAPI } from '@/api/user.js';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/userStore.js';

const userStore = useUserStore();
const form = ref({
  username: 'admin',
  password: '123456',
});

const rules = {
  username: [
    { required: true, message: '必须输入账号', trigger: 'blur' },
    { min: 1, max: 10, message: '必须是1位以上10位以下', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '必须输入密码',
      trigger: 'blur',
    },
    { min: 4, message: '必须是4位以上', trigger: 'blur' },
  ],
};

const formRef = ref(null);
const router = useRouter();

function loginbtn() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const info = await loginAPI({ username: form.value.username, password: form.value.password });
      console.log(info);
      if (info.code === '200') {
        ElMessage({
          showClose: true,
          message: '登录成功',
          type: 'success',
        });
        localStorage.token = info.data.token;
        localStorage.avatar = info.data.employee.avatar;
        userStore.getUserInfo();
        userStore.avatar = info.data.employee.avatar;
        router.replace({ path: '/' });
      } else {
        ElMessage({
          showClose: true,
          message: '用户名或密码错误',
          type: 'error',
        });
      }
    }
  });
}
</script>

<style scoped lang="less">
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('@/assets/login-bg.svg');

  .form {
    .el-card {
      border: none;
      padding: 0;
    }

    h1 {
      padding-left: 20px;
      font-size: 24px;
    }

    .el-input {
      height: 44px;
    }
  }
}
</style>
